<template>
  <div class="user-profile">
    <h1>个人中心</h1>

    <div v-if="loading" class="loading">加载中...</div>

    <div v-if="errorMessage" class="error-message">
      <span class="error-icon">⚠️</span>
      <span class="error-text">{{ errorMessage }}</span>
    </div>

    <div v-if="userInfo" class="profile-container">
      <div class="profile-card">
        <h2>当前用户信息</h2>
        <div class="info-grid">
          <div class="info-item">
            <img src="@/assets/乌萨奇2.png" class="info-icon" alt="用户ID图标" />
            <span class="info-label">用户ID:</span>
            <span class="info-value">{{ userInfo.id }}</span>
          </div>
          <div class="info-item">
            <img src="@/assets/乌萨奇1.png" class="info-icon" alt="用户名图标" />
            <span class="info-label">用户名:</span>
            <span class="info-value">{{ userInfo.username }}</span>
          </div>
          <div class="info-item">
            <img src="@/assets/奶龙1.png" class="info-icon" alt="性别图标" />
            <span class="info-label">性别:</span>
            <span class="info-value">{{ userInfo.sex }}</span>
          </div>
          <div class="info-item">
            <img src="@/assets/小八1.png" class="info-icon" alt="年龄图标" />
            <span class="info-label">年龄:</span>
            <span class="info-value">{{ userInfo.age || '未设置' }}</span>
          </div>
          <div class="info-item">
            <img src="@/assets/曼波1.png" class="info-icon" alt="电话图标" />
            <span class="info-label">电话:</span>
            <span class="info-value">{{ userInfo.phone || '未设置' }}</span>
          </div>
          <div class="info-item">
            <img src="@/assets/曼波3.png" class="info-icon" alt="角色图标" />
            <span class="info-label">角色:</span>
            <span class="info-value">{{ userInfo.role }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <RouterLink  to="/user-edit" class="edit-btn">
        编辑信息
      </RouterLink>
      <button class="logout-btn" @click="handleLogout">退出登录</button>
      <button class="delete-account-btn" @click="handleDeleteAccount" :disabled="isDeleting">
        {{ isDeleting ? '注销中...' : '注销账户' }}
      </button>
      <!-- 仅用户角色显示授权管理按钮 -->
      <RouterLink v-if="userInfo && userInfo.role === '用户'" to="/user-profile/authorization" class="authorization-btn">
        授权管理
      </RouterLink>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { RouterLink, useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const userInfo = ref(null);
const loading = ref(true);
const errorMessage = ref('');
const isSubmitting = ref(false);
const isDeleting = ref(false);

// 从localStorage获取用户信息
onMounted(() => {
  try {
    const storedUser = localStorage.getItem('currentUser');
    if (storedUser) {
      userInfo.value = JSON.parse(storedUser);
      console.log('当前用户信息:', userInfo.value);
    } else {
      errorMessage.value = '未找到用户信息，请先登录';
    }
  } catch (error) {
    errorMessage.value = '加载用户信息失败';
  } finally {
    loading.value = false;
  }
});

// 退出登录功能
const handleLogout = () => {
  if (confirm('确定要退出登录吗？')) {
    localStorage.removeItem('currentUser');
    // 发送用户登出事件通知导航栏更新
    window.dispatchEvent(new Event('user-logout'));
    router.push('/login');
  }
};

// 注销账户功能
const handleDeleteAccount = async () => {
  if (!confirm('警告：注销账户将删除所有数据，且无法恢复！\n确定要注销账户吗？')) {
    return;
  }

  if (!userInfo.value || !userInfo.value.id) {
    errorMessage.value = '无法获取用户信息，无法执行注销操作';
    return;
  }

  isDeleting.value = true;
  errorMessage.value = '';

  try {
    const response = await fetch(`http://localhost:8080/api/users/${userInfo.value.id}`, { 
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      },
    });

    const result = await response.json();
    if (!response.ok || !result.success) {
      throw new Error(result.message || '注销账户失败');
    }
    // 注销成功，清除本地存储并跳转至注册页面
    localStorage.removeItem('currentUser');
    // 发送用户登出事件通知导航栏更新
    window.dispatchEvent(new Event('user-logout'));
    alert('账户注销成功');
    router.push('/register');
  } catch (error) {
    errorMessage.value = '注销失败：' + (error.message || '未知错误');
  } finally {
    isDeleting.value = false;
  }
};
</script>

<style scoped>
.user-profile {
  max-width: 800px;
  margin: 80px auto 2rem;
  padding: 2rem;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.loading {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.error-message {
  color: #d43f3a;
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  padding: 10px 15px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.error-icon {
  margin-right: 8px;
  font-size: 16px;
}

.profile-container {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.profile-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 1rem;
  margin-top: 1rem;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-icon {
  width: 40px;
  height: 40px;
  margin-right: 8px;
}

.info-label {
  color: #666;
  width: 80px;
}

.info-value {
  flex: 1;
}

.action-buttons {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
  flex-wrap: wrap;
}

.edit-btn,
.logout-btn,
.delete-account-btn,
.authorization-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  text-decoration: none;
  font-size: 14px;
  display: inline-block;
  text-align: center;
}

.edit-btn {
  background-color: #409eff;
  color: white;
  border: none;
}

.logout-btn {
  background-color: #67c23a;
  color: white;
  border: none;
}

.delete-account-btn {
  background-color: #f56c6c;
  color: white;
  border: none;
}

.authorization-btn {
  background-color: #909399;
  color: white;
  border: none;
}

.edit-btn:disabled,
.logout-btn:disabled,
.delete-account-btn:disabled,
.authorization-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>